/*
   @Copyright:LintCode
   @Author:   tjyemail
   @Problem:  http://www.lintcode.com/problem/spiral-matrix-ii
   @Language: C++
   @Datetime: 17-03-09 13:44
   */

class Solution {
public:
	/**
	 * @param n an integer
	 * @return a square matrix
	 * Tip: See also problem 374 spiral-matrix
	 */
	vector<vector<int> > generateMatrix(int n) {
		// Write your code here
		vector<vector<int> > mat(n,vector<int>(n,0));
		for(int l=0, r=n-1, t=0, b=n-1, c=0;
			l<=r && t<=b; ++l,--r,++t,--b) {
			for (int i=l; i<=r; mat[t][i++]=++c);
			for (int i=t+1; i<b; mat[i++][r]=++c);
			for (int i=r; i>=l && t<b; mat[b][i--]=++c);
			for (int i=b-1; i>t && l<r; mat[i--][l]=++c);
		}
		return mat;
	}
};
